import { fetchList, uploadFile, addProduct, deleteProduct, updateProduct, updateProductItem, addProductItem, deleteProductItem, updateProductParam } from '@/api/product'
import Pagination from '@/components/Pagination'
import { provinceAndCityData, regionData, provinceAndCityDataPlus, regionDataPlus, CodeToText, TextToCode } from 'element-china-area-data'

export default {
  name: 'Product',
  components: { Pagination },
  data() {
    return {
      area_options: provinceAndCityData,
      CodeToText: CodeToText,
      selected_area: null,
      area_list: [],
      categoryOptions: [{
        value: 0,
        label: '全部'
      }],
      subCategoryOptions: [{
        value: 0,
        label: '全部'
      }],
      zone_options: [
        {
          value: '',
          label: '请选择',
        },
        {
          value: '1',
          label: 'A区',
        },
        {
          value: '2',
          label: 'B区',
        },
        {
          value: '3',
          label: 'C区',
        },
        {
          value: '5',
          label: 'D区',
        },
        {
          value: '6',
          label: 'E区',
        },
        {
          value: '4',
          label: 'T区',
        },
      ],
      image_file_ids: [],
      cateList: [],
      fileList: [],
      deleteItemList: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        category: 0,
        sub_category: 0,
        category_id: '',
        product_name: '',
        keyword: ''
      },
      temp: {
        category_id: '',
        name: '',
        hot: 1,
        sell: 0,
        description: '暂无描述',
        detail: '暂无描述',
        warehouse_id: '1',
        image_file_id: [],
        cover_file_id: null,
        package: '',
        items: [{
          name: '',
          price: '',
          stock: '',
          min_stock: '',
          max_stock: '',
          member_price: '',
          purchase_price: '',
          area_id: '',
          zone: '',
          shelf: '',
          floor: '',
          number: '',
          weight: 0,
          sku_no:'',
        }]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        category_id: [{ required: true, message: '请选择分类', trigger: 'change' }],
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  async created() {
    this.getList()
    const cateList = await this.$store.dispatch('product/getCateList')
    this.cateList = cateList
    this.categoryOptions = this.categoryOptions.concat(cateList)
  },
  methods: {
    onSelectedArea(v){
      let area_list = this.area_list
      let flag = false;
      for(let i=0;i<area_list.length;i++){
        if(v[1] == area_list[i]){
          flag = true;
          break
        }
      }
      if(!flag){
        area_list.push(v[1])
        this.area_list = area_list
      }
    },
    onCancelArea(v){
      let area_list = this.area_list
      for(let i=0;i<area_list.length;i++){
        if(v == area_list[i]){
          area_list.splice(i,1)
        }
      }
      this.area_list = area_list
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.products
        this.total = response.total
        this.listLoading = false
      }).catch(error => {
        this.list = []
        this.total = 0
        this.listLoading = false
        Promise.reject(error)
      })
    },
    handleAddItem() {
      this.temp.items.push({
        name: '',
        stock: '',
        min_stock: '',
        price: '',
        member_price: '',
        purchase_price: ''
      })
    },
    handleAddItemCopy() {
      const item = this.temp.items[0]
      this.temp.items.push({
        name: item.name,
        price: item.price,
        member_price: item.member_price,
        purchase_price: item.purchase_price,
        stock: item.stock,
        min_stock: item.min_stock,
        max_stock: item.max_stock
      })
    },
    handleDeleteItem(row, index) {
      if (this.temp.items.length === 1) {
        this.$notify.error({
          title: '失败',
          message: '至少保留一个规格',
          duration: 2000
        })
        return
      }
      if (row.id) {
        this.deleteItemList.push(row.id)
      }
      this.temp.items.splice(index, 1)
    },
    onRemovePic(file, fileList) {
      const list = this.image_file_ids
      for (let i = 0, len = list.length; i < len; i++) {
        if (list[i].uid === file.uid) {
          this.image_file_ids.splice(i, 1)
          break
        }
      }
    },
    async handleUploadPic(data) {
      const formData = new FormData()
      formData.append('file', data.file)
      const res = await uploadFile(formData)
      const list = this.image_file_ids
      list.push({
        uid: data.file.uid,
        fid: res.file.id
      })
      this.image_file_ids = list
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },

    resetTemp() {
      this.temp = {
        category_id: '',
        name: '',
        hot: 1,
        sell: 1,
        description: '暂无描述',
        detail: '暂无描述',
        warehouse_id: '1',
        image_file_id: [],
        cover_file_id: null,
        package: '',
        items: [{
          name: '',
          price: '',
          member_price: '',
          purchase_price: '',
          stock: '',
          min_stock: '',
          max_stock: '',
          area_id: '',
          zone: '',
          shelf: '',
          floor: '',
          number: '',
          weight: 0,
          sku_no: ''
        }]
      }
      this.fileList = []
    },

    handleCreate() {
      this.resetTemp()
      this.image_file_ids = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.image_file_ids.length === 0) {
            this.$message({
              message: '请至少上传一张主图',
              type: 'error'
            })
            return
          }
          const data = this.temp
          let nullFlag = false
          data.items.forEach(item => {
            item.cover_file_id = this.image_file_ids[0].fid
            if (item.name === '' || item.price === '' || item.stock === '' || item.member_price === '' || item.purchase_price === '' || item.min_stock === '' || item.max_stock === '') {
              this.$message({
                message: '规格信息不能为空',
                type: 'error'
              })
              nullFlag = true
            }
          })
          if (nullFlag) {
            return
          }
          const imageList = []
          let flag = false
          data.category_id = data.category_id[1]
          this.image_file_ids.forEach(item => {
            imageList.push(item.fid)
            if (data.cover_file_id === item.fid) {
              // eslint-disable-next-line no-const-assign
              flag = true
            }
          })
          if (!flag) {
            data.cover_file_id = imageList[0]
          }
          data.image_file_id = imageList
          if (!data.cover_file_id) {
            data.cover_file_id = data.image_file_id[0]
          }
          addProduct(data).then(res => {
            this.list.unshift(res.product)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    handleUpdate(row) {
      this.deleteItemList = []
      this.temp = Object.assign({}, row) // copy obj
      this.temp.category_id = []
      this.temp.category_id.push(row.category.parent.id)
      this.temp.category_id.push(row.category.id)
      this.temp.cover_file_id = row.cover.id
      this.fileList = row.images
      this.fileList.forEach(item => {
        item.uid = item.id
      })
      const list = []
      row.images.forEach(item => {
        list.push({
          uid: item.id,
          fid: item.id
        })
      })
      this.image_file_ids = list
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      if(row.excluded_area){
        let area_list = row.excluded_area.split('|')
        this.area_list = area_list
      }else{
        this.area_list = []
      }
    },

    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.image_file_ids.length === 0) {
            this.$message({
              message: '请至少上传一张主图',
              type: 'error'
            })
            return
          }
          const tempData = Object.assign({}, this.temp)
          tempData.warehouse_id = '1'
          let nullFlag = false
          tempData.items.forEach(item => {
            item.cover_file_id = this.image_file_ids[0].fid
            if (!item.area_id || !item.shelf || !item.floor || !item.number) {
              this.$message({
                message: '库位信息不能为空',
                type: 'error'
              })
              nullFlag = true
            }
          })
          if (nullFlag) {
            return
          }
          tempData.category_id = tempData.category_id[1]
          const imageList = []
          let flag = false
          this.image_file_ids.forEach(item => {
            imageList.push(item.fid)
            if (tempData.cover_file_id === item.fid) {
              flag = true
            }
          })
          if (!flag) {
            tempData.cover_file_id = imageList[0]
          }
          tempData.image_file_id = imageList
          tempData.items.forEach(async function(item) {
            if (item.id) {
              await updateProductItem(tempData.id, item.id, item)
            } else {
              await addProductItem(tempData.id, item)
            }
          })
          this.deleteItemList.forEach(async function(item) {
            await deleteProductItem(tempData.id, item)
          })


          const area_list = this.area_list
          let excluded_area = ''
          area_list.forEach(v=>{
            excluded_area += v + '|'
          })
          excluded_area = excluded_area.substr(0,excluded_area.length-1)
          if(excluded_area && '' != excluded_area){
            tempData.excluded_area = excluded_area
          }else{
            tempData.clear_excluded_area = true;
          }
          updateProduct(tempData.id, tempData).then(res => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, res.product)
            this.dialogFormVisible = false
            this.area_list = [],
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    handleParamChange: async function(val,row,param){
      let data = {}
      data[param] = val
      row[param] = val
      let res = await updateProductParam(row.id,data)
      if(res){
        let index = this.list.findIndex(v => v.id === row.id)
        this.list.splice(index, 1, row)
      }
    },

    handleCreateCopy(row) {
      this.resetTemp()
      this.deleteItemList = []
      this.image_file_ids = []
      this.temp = Object.assign({}, row) // copy obj
      this.temp.category_id = []
      this.temp.category_id.push(row.category.parent.id)
      this.temp.category_id.push(row.category.id)
      this.temp.warehouse_id = row.warehouse.id
      this.temp.package = row.package
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.temp.items.forEach(item =>{
        item.id = null
      })
    },

    handleDelete(row, index) {
      this.$confirm('是否确定删除商品？删除后无法找回', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProduct(row.id).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        }).catch(error => {
          Promise.reject(error)
        })
      })

    },

    handleSelectChange() {
      const id = this.listQuery.category
      const list = [{
        value: 0,
        label: '全部'
      }]
      if (id === 0) {
        this.subCategoryOptions = list
      } else {
        const index = this.categoryOptions.findIndex(v => v.value === id)
        const item = this.categoryOptions[index]
        this.subCategoryOptions = list.concat(item.children)
      }
      this.listQuery.sub_category = 0
      this.handleSearch()
    },

    handleSearch() {
      this.list = []
      this.listQuery.page = 1
      this.getList()
    },

    onPreview(e) {
      this.image_file_ids.forEach(item => {
        if (e.uid === item.uid) {
          this.temp.cover_file_id = item.fid
          this.$notify({
            title: '成功设置主图',
            type: 'success',
            duration: 1000
          })
        }
      })
    }
  }
}
